﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Imports httpWebClient.HttpWebClient

Partial Class Control_TiepNhan_TraCuu
    Inherits System.Web.UI.UserControl
    Dim itm As New ListItem("--- Chọn ---", "")
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            'xu ly jquery khi post back
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
        End If
    End Sub

    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1, Optional ByVal strSearch As String = "")
        Using data As New VSEntities
            'So ban ghi muon the hien tren trang
            Dim arrSearch() As String = {iPage.ToString, strSearch}
            ViewState("search") = arrSearch
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            Dim p = (From q In data.CertifiedHouseholds Where (q.CertifiedCode.Contains(strSearch) Or q.Ow_CardID.Contains(strSearch) Or q.Ow_TaxCode.Contains(strSearch)) Order By q.CertifiedID Descending Select q).Skip((iPage - 1) * intPag_Size).Take(intPag_Size).ToList
            Dim strKey_Name() As String = {"CertifiedID", "Ow_Provider_ID", "ProvinceId", "ParentId", "CertifiedCode"}
            'Tong so ban ghi
            hidCount.Value = p.Count
            Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(CInt(lnkTile.ToolTip), arrSearch(1))
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub
#End Region
#Region "Event for control"
    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Using data As New VSEntities
            intId = grdShow.DataKeys(hidID.Value)("CertifiedID").ToString
            Dim q = (From p In data.CertifiedHouseholds Where p.CertifiedID = intId Select p).FirstOrDefault
            Try
                data.CertifiedHouseholds.DeleteObject(q)
                data.SaveChanges()
                Insert_App_Log("Insert  CertifiedHousehold:" & q.CertifiedCode & "", Function_Name.CertifiedHousehold, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công.');", Me.Page, True)
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub

    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1
            Dim hplCertifiedcode As HyperLink = CType(e.Row.FindControl("hplCertifiedcode"), HyperLink)
            '   hplCertifiedcode.NavigateUrl = "../../Page/CertifiedHousehold/Detail.aspx?Certifiedid=" & grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString
            If Not grdShow.DataKeys(e.Row.RowIndex)("CertifiedCode") Is Nothing Then
                hplCertifiedcode.Text = grdShow.DataKeys(e.Row.RowIndex)("CertifiedCode").ToString

            End If
            Dim lblLoaiHoSo As Label = CType(e.Row.FindControl("lblLoaiHoSo"), Label)
            If Not grdShow.DataKeys(e.Row.RowIndex)("ParentId") Is Nothing Then
                lblLoaiHoSo.Text = IIf(grdShow.DataKeys(e.Row.RowIndex)("ParentId").ToString <> grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString, "Cấp đổi", "Cấp mới")
            Else
                lblLoaiHoSo.Text = "Cấp mới"
            End If

            Dim lblHuyen As Label = CType(e.Row.FindControl("lblHuyen"), Label)
            Using _data As New VSEntities
                Dim _ProvinceId As Integer = grdShow.DataKeys(e.Row.RowIndex)("ProvinceId")
                Dim p = (From q In _data.Provinces Where q.Id = _ProvinceId Select q).FirstOrDefault
                If Not p Is Nothing Then
                    lblHuyen.Text = p.Title
                End If

                'trang thai
                Dim lblTrangThai As Label = CType(e.Row.FindControl("lblTrangThai"), Label)
                Dim _Id As Integer = grdShow.DataKeys(e.Row.RowIndex)("CertifiedID")
                Dim _Code As String = grdShow.DataKeys(e.Row.RowIndex)("CertifiedCode")
                Dim _ListCode = (From q In _data.CertifiedHouseholds
                            Where q.CertifiedCode = _Code Select q).Count
                If _ListCode > 1 Then
                    Dim _DangHoatDong = (From q In _data.CertifiedHouseholds
                                         Where q.CertifiedCode = _Code Order By q.CertifiedDate Descending Select q.CertifiedID).FirstOrDefault
                    If _DangHoatDong = _Id Then
                        Dim _Ngung = (From q In _data.CertifiedChamDuts
                                Where q.CertifiedID = _Id Select q).FirstOrDefault
                        If Not _Ngung Is Nothing Then
                            lblTrangThai.Text = "Chấm dứt"
                        End If

                        Dim _TamNgung = (From q In _data.CertifiedTamNgungs
                                         Where q.CertifiedID = _Id Select q).FirstOrDefault
                        If Not _TamNgung Is Nothing Then
                            lblTrangThai.Text = "Tạm ngưng"
                        End If

                        If _Ngung Is Nothing And _TamNgung Is Nothing Then
                            lblTrangThai.Text = "Đang hoạt động"
                        End If
                    Else
                        Dim _Ngung = (From q In _data.CertifiedChamDuts
                                Where q.CertifiedID = _Id Select q).FirstOrDefault
                        If Not _Ngung Is Nothing Then
                            lblTrangThai.Text = "Chấm dứt"
                        End If

                        Dim _TamNgung = (From q In _data.CertifiedTamNgungs
                                         Where q.CertifiedID = _Id Select q).FirstOrDefault
                        If Not _TamNgung Is Nothing Then
                            lblTrangThai.Text = "Tạm ngưng"
                        End If

                        If _Ngung Is Nothing And _TamNgung Is Nothing Then
                            lblTrangThai.Text = "Đã đổi"
                        End If

                    End If

                Else
                    Dim _Ngung = (From q In _data.CertifiedChamDuts
                                Where q.CertifiedID = _Id Select q).FirstOrDefault
                    If Not _Ngung Is Nothing Then
                        lblTrangThai.Text = "Chấm dứt"
                    End If

                    Dim _TamNgung = (From q In _data.CertifiedTamNgungs
                                     Where q.CertifiedID = _Id Select q).FirstOrDefault
                    If Not _TamNgung Is Nothing Then
                        lblTrangThai.Text = "Tạm ngưng"
                    End If

                    If _Ngung Is Nothing And _TamNgung Is Nothing Then
                        lblTrangThai.Text = "Đang hoạt động"
                    End If
                End If

            End Using



        End If
    End Sub
#End Region
#Region "Search"
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        BindToGrid(1, txtOw_cardid.Text.Trim())
        'Dim url As String = "http://www.gdt.gov.vn/wps/portal/!ut/p/b1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOINTCw9fSzCgv2dzLxdDTxDHV2NLAM8jC3CzPQLsh0VAVXv_MU!/"
        'Dim postdata=
        '        result = WebInstance.SendPostRequest(_url.RootUrl + "/wager/CreateWager.aspx?WT=11&lg=" + lg + "&sel=" + item.OddsId, postingData);

        '        var document = new HtmlDocument();
        '        document.LoadHtml(result);

    End Sub
    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1, arrSearch(1))
    End Sub
#End Region
End Class